package com.example.xunua_today_in_history.Adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.xunua_today_in_history.R;
import com.example.xunua_today_in_history.bean.HistoryBean;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

public class HistoryAdapter extends BaseAdapter {
    private List<HistoryBean.ResultBean> mdata;
    private Context context;

    public HistoryAdapter(ArrayList<HistoryBean.ResultBean> mdata, Context context) {
        this.mdata = mdata;
        this.context = context;
    }

    @Override
    public int getCount() {
        return mdata.size();
    }

    @Override
    public Object getItem(int position) {
        return mdata.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder=null;
        if (convertView == null) {
            convertView= LayoutInflater.from(context).inflate(R.layout.item_lv_main,null);
            holder=new ViewHolder();
            holder.line=convertView.findViewById(R.id.lv_line);
            holder.tv_time=convertView.findViewById(R.id.lv_tv_time);
            holder.tv_title=convertView.findViewById(R.id.lv_tv_title);
            holder.img=convertView.findViewById(R.id.lv_img);
            convertView.setTag(holder);
        }else {
            holder= (ViewHolder) convertView.getTag();
        }
        //拿出数据
        HistoryBean.ResultBean resultBean=mdata.get(position);
        //判断年份是否和上一个年份相同  如果相同就不显示年份  不相同则显示年份
        if (position != 0) {
            HistoryBean.ResultBean lastBean=mdata.get(position-1);
            if (resultBean.getYear() == lastBean.getYear()) {
                holder.line.setVisibility(View.GONE);
            }else {
                holder.line.setVisibility(View.VISIBLE);  //不相同则显示
            }
        }else {
            holder.line.setVisibility(View.VISIBLE);   //第一条必须显示时间栏
        }
        holder.tv_time.setText(resultBean.getYear()+"-"+resultBean.getMonth()+"-"+resultBean.getDay());
        holder.tv_title.setText(resultBean.getTitle());
        String pic = resultBean.getPic();
        if (pic.isEmpty()){
            holder.img.setVisibility(View.GONE);
        }else {
            holder.img.setVisibility(View.VISIBLE);
            Picasso.with(context).load(pic).into(holder.img);
        }
        return convertView;
    }
    private class ViewHolder{
        private TextView tv_time,tv_title;
        private ImageView img;
        private LinearLayout line;
    }
}
